package com.flycms.modules.user.Interceptor;

import com.flycms.common.constant.Constants;
import com.flycms.common.constant.HttpStatus;
import com.flycms.common.utils.CheckUrlUtils;
import com.flycms.modules.user.util.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 登陆拦截器
 * 配置拦截器的内容在：com.imooc.passbook.passbook.config.WebLoginConfig 中
 * */
@Component
public class LoginHandle extends HandlerInterceptorAdapter {
    @Autowired
    private  JwtTokenUtils jwtTokenUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        String[] excludeUrl = new String[]{"/wx/auth/**","/system/**","/login","/getInfo","/getRouters"};
        if(CheckUrlUtils.checkWhiteList(excludeUrl, url)) {
            //开放地址 不与拦截
            return Boolean.TRUE;
        }
        if (!StringUtils.isEmpty(request.getHeader(Constants.JWT_AUTHORITIES))) {
            String token = request.getHeader(Constants.JWT_AUTHORITIES);
            //将 token 放入线程本地变量
            //todo 验证用户token 是否有效
            if(!jwtTokenUtils.tokenValidate(token)){
                //TokenUtil.removeToken();
                response.setStatus(HttpStatus.FORBIDDEN);
                throw new RuntimeException("用户身份已过期");

            }

            response.addHeader("token", jwtTokenUtils.generateToken(1l));
            //TokenUtil.setToken(token);
            //System.out.println(TokenUtil.getToken()+" ===== already login");
            return true;
        } else {
            response.setStatus(HttpStatus.NOT_FOUND);
            throw new RuntimeException("用户token 缺失");

        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        //清除token信息
        //TokenUtil.removeToken();
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}
